package com.changgou.web.controller;

import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.order.feign.CartFeign;
import com.changgou.order.feign.OrderFeign;
import com.changgou.order.pojo.Order;
import com.changgou.order.pojo.OrderItem;
import com.changgou.user.feign.AddressFeign;
import com.changgou.user.pojo.Address;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/worder")
public class OrderController {

    @Autowired
    private AddressFeign addressFeign;

    @Autowired
    private CartFeign cartFeign;

    @Autowired
    private OrderFeign orderFeign;


    /**
     * 新增订单
     *
     * @param order
     * @return
     */
    @PostMapping("/add")
    @ResponseBody
    public Result add(@RequestBody Order order) {

        return orderFeign.add(order);
    }

    /**
     * 准备订单页
     *
     * @param model
     * @return
     */
    @GetMapping("/ready/order")
    public String readyOrder(Model model) {

        //获取地址列表
        List<Address> addressList = addressFeign.list().getData();

        //添加默认收件人
        for (Address address : addressList) {
            if ("1".equals(address.getIsDefault())) {
                model.addAttribute("defaultAddress", address);
                break;
            }
        }

        model.addAttribute("address", addressList);
        //获取购物车列表
        Map map = cartFeign.list();
        List<OrderItem> orderItemList = (List<OrderItem>) map.get("orderItemList");
        model.addAttribute("carts", orderItemList);
        Integer totalNum = (Integer) map.get("totalNum");
        model.addAttribute("totalNum", totalNum);
        Integer totalMoney = (Integer) map.get("totalMoney");
        model.addAttribute("totalMoney", totalMoney);
        return "order";
    }

    @GetMapping("/toPayPage")
    public String readyOrder(@RequestParam String orderId, Model model) {

        Result<Order> orderResult = orderFeign.findById(orderId);
        Order order = orderResult.getData();
        model.addAttribute("orderId", orderId);
        model.addAttribute("payMoney", order.getPayMoney());
        return "pay";
    }
}
